package legumes.client.ui.basket.slate;

import legumes.client.resources.PNResources;
import legumes.client.services.callbacks.SaveStallCallback;
import legumes.client.services.util.rpc.RPCCallSequencer;
import legumes.client.ui.widgets.form.item.MaxDeliveryableProductsIntItem;
import legumes.client.ui.widgets.form.item.PriceFloatItem;
import legumes.client.ui.widgets.utils.Formatters;
import legumes.shared.domain.Stall;

import com.google.gwt.core.client.GWT;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.widgets.Canvas;
import com.smartgwt.client.widgets.Window;
import com.smartgwt.client.widgets.events.CloseClickHandler;
import com.smartgwt.client.widgets.events.CloseClientEvent;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.ButtonItem;
import com.smartgwt.client.widgets.form.fields.events.ClickEvent;
import com.smartgwt.client.widgets.form.fields.events.ClickHandler;
import com.smartgwt.client.widgets.layout.HLayout;

public abstract class BasketPropertiesEditor extends Window {

	private DynamicForm form;
	private PriceFloatItem  priceFloatItem;
	private MaxDeliveryableProductsIntItem nbBasketMaxIntItem;
	private Stall stall;
	private ButtonItem biValidate;
	private ButtonItem biCancel;
	
	private float price;
	private int nbBasketMax;
	
	public BasketPropertiesEditor(Stall stall_){
		stall = stall_;
		setWidth(480);
		setHeight(200);
		String titleWindow = "Edition du panier";
		setTitle("<img src=\""
				+ PNResources.INSTANCE.editIcon().getURL()
				+ "\" />&nbsp;" + titleWindow);

		setShowCloseButton(true);
		setShowMinimizeButton(false);
		setCanDrag(true);
		setCanDragReposition(true);
		setIsModal(true);
		setShowModalMask(true);  
		setAutoCenter(true);
		addCloseClickHandler(new CloseClickHandler() {  
            public void onCloseClick(CloseClientEvent event) {  
                destroy();  
            }  
        });  
		buildPanel();
		show();
		priceFloatItem.focusInItem();
	}

	private void buildPanel() {
		HLayout mainLayout = new HLayout();
		mainLayout.setMargin(10);
		
		mainLayout.setMembers( buildFormPanel() );
		
		addItem(mainLayout);
	}
	
	protected abstract float getMenuBasketPrice();
	protected abstract int getMaxMenuBasket();
	protected abstract void setMenuBasketPrice(float basketPrice_);
	protected abstract void setMaxMenuBasket(int maxMenuBasket);
	protected abstract void onPropertiesSaved(float basketPrice_, int maxMenuBasket);
	
	private Canvas buildFormPanel(){
		form = new DynamicForm();
		form.setPadding(5);  
		form.setWidth("*");
		form.setLayoutAlign(Alignment.CENTER);
		form.setNumCols(2);
		form.setValidateOnExit(true);
		
		priceFloatItem = new PriceFloatItem();
		priceFloatItem.setStartRow(true);
		priceFloatItem.setEndRow(true);
		priceFloatItem.setValue(getMenuBasketPrice());
		
		nbBasketMaxIntItem = new MaxDeliveryableProductsIntItem();
		nbBasketMaxIntItem.setValue(getMaxMenuBasket());
    	
		biValidate = new ButtonItem("AddToBasket", "Mettre à jour");
    	biValidate.setAutoFit(true);
    	biValidate.setColSpan(1);
    	biValidate.setAlign(Alignment.CENTER);
    	biValidate.setStartRow(true);
    	biValidate.setEndRow(false);
    	biValidate.setIcon( PNResources.INSTANCE.addIcon().getURL() );
    	biValidate.addClickHandler( createClickhandler() );
    	
    	biCancel = new ButtonItem("RemoveFromBasket", "Annuler");
    	biCancel.setIcon( PNResources.INSTANCE.cancelIcon().getURL() );
    	biCancel.setAlign(Alignment.CENTER);
    	biCancel.setStartRow(false);
    	biCancel.setEndRow(false);
    	biCancel.addClickHandler( new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				BasketPropertiesEditor.this.destroy();
			}
		});
    	
    	form.setFields(priceFloatItem, nbBasketMaxIntItem, biValidate, biCancel);

        return form;
	}
	

	private ClickHandler createClickhandler(){
		return new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				if( form.validate() ){
					try{
						float price = Formatters.extractFloat( priceFloatItem.getValueAsString());
						int nbBasketMax = Formatters.extractInteger( nbBasketMaxIntItem.getValue() );
						
						setMenuBasketPrice(price);
						setMaxMenuBasket(nbBasketMax);
						
						saveOnServer();
					} catch(Exception e_){
						GWT.log("BasketPropertiesEditor : onEditComplete ", e_);
					}
					
				}
            }
		};
	}
	
	private void saveOnServer(){
		RPCCallSequencer callSequencer = new RPCCallSequencer("Enregistrement en cours...");
		
		final SaveStallCallback saveStallCallback = new SaveStallCallback(stall);
		callSequencer.addCall(saveStallCallback);
		callSequencer.addRunnable(new Runnable() {
			public void run() {
				onPropertiesSaved(price, nbBasketMax);
				BasketPropertiesEditor.this.destroy();
			}
		});
		callSequencer.callSequence();
	}
}
